const FormData = require("form-data");
const axios = require("axios").default.create({
  headers: {
    "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.34 (KHTML, like Gecko) Chrome/62.0.3325.180 Safari/537.35 OPR/52.0.2871.41"
  }
});
const fs = require("fs");
const CommonAxerrHG = require("./CommonAxerrHandlerGenerator").CommonAxerrHandlerGen;
const Toolbox = require("./Toolbox");
const util = require("util");
const path = require("path");



const UPLOAD_URL = "https://file-dd.jd.com/file/uploadImg.action";


/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
 * @param {String} file_path 
 */
function uploadImage(file_path) {
  return new Promise(resolve => {
    let form = new FormData;
    let filestream = fs.createReadStream(file_path);

    form.append("upload", filestream, {
      filename: `${Math.random()}.${path.basename(file_path)}`
    });
    form.append("callback", "h-callback");

    axios.post(UPLOAD_URL, form, {
      headers: {
        ...form.getHeaders(),
      },
      maxContentLength: Number.MAX_SAFE_INTEGER
    }).then(axresp => {
      if (axresp.data && util.isString(axresp.data)
        && axresp.headers["content-type"].includes("text/html")
        && axresp.data.includes("360buyimg")) {
        /**@type {String} */
        let d = axresp.data
        let matched = d.match(/<body>(.*)<\/body>/);
        if (matched && matched.length == 2) {
          try {
            let j = JSON.parse(matched[1]);
            if (j.path && util.isString(j.path)) {
              return resolve({
                ok: true,
                msg: "ok",
                data: {
                  link: j.path
                }
              })
            }
            throw new Error(`can not find 'path' in json:${matched[1]}`)
          } catch (e) {
            // do nothing
          }
        }
      }
      debugger
      throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
    }).catch(axerr => {
      CommonAxerrHG(resolve)(axerr);
    })
  })
}




module.exports = {
  uploadImage
}